<?php
/**
 * check user in black list by tong dun interface
 * User: csyr
 * Date: 16/7/23
 * Time: 下午3:05
 */

namespace Home\Common\Hook;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Curl\Curl;
use Common\Vendor\Hook\BaseHook;
use Think\Log;

class BlackCheck extends BaseHook
{
    public $apiUrl = 'https://apitest.tongdun.cn/riskService';

    public function execute($data, $param = [])
    {
        if (isset($param['partner_code'], $param['secret_key'], $param['event_id'], $param['api_url'], $data['id'])) {

            $this->apiUrl = $param['api_url'];
            //$customerId = $data['id'];

             $event_id = $param['event_id']; //默认值 借款事件
            /**/
            if($data['hook_action']==1) {
                //注册
                $event_id = $param['event1_id'];
            }
            if($data['hook_action']==2) {
                //借款
                $event_id = $param['event2_id'];
            }
            if($data['hook_action']==3) {
                //交易
                $event_id = $param['event3_id'];
            }
            if($data['hook_action']==4) {
                //调额
                $event_id = $param['event4_id'];
            }
            if($data['hook_action']==5) {
                //预筛事件
                $event_id = $param['event5_id'];
            }

            $secret_key = $param['secret_key'];
            if($data['hook_action'] == 5) {
                $secret_key = $param['secret_key5'];
            }
            // 准备接口参数
            $requestData = array(
                "partner_code" => $param['partner_code'],
                "secret_key" => $secret_key,
                "event_id" => $event_id,
            );
            !empty($data['real_name']) && $requestData['account_name'] = $data['real_name'];
            !empty($data['id_num']) && $requestData['id_number'] = $data['id_num'];
            !empty($data['mobile']) && $requestData['account_mobile'] = $data['mobile'];
            //!empty($data['device_id']) && $requestData['device_id'] = $data['device_id'];
            if($data['hook_action'] == 1 ||$data['hook_action'] == 2 || $data['hook_action'] == 3 || $data['hook_action'] == 4) {
                !empty($data['tongdun_device_id']) && $requestData['black_box'] = $data['tongdun_device_id'];
                $requestData['ext_selfdevid'] = 1; //同盾设备白名单参数（0表示平台业务员设备，1表示c端用户个人设备。）
            }
            /**/
            if($data['hook_action'] == 3 || $data['hook_action'] == 4 ) {
                //交易和调额需要入参
                !empty($data['tongdun_application_id']) && $requestData['application_id'] = $data['tongdun_application_id'];
            }
            if($data['hook_action'] == 2) {
                $requestData['resp_detail_type'] = 'application_id'; //默认借款事件需要入参
            }
            /**/
            if($data['hook_action'] == 1 || $data['hook_action'] == 3 || $data['hook_action'] == 4 ) {
                $requestData['resp_detail_type'] = 'device';
            }
            

            // 调用接口final_score
            Log::write("BLACK-CHECK-RESULT_DATA:".json_encode($requestData), Log::INFO);
            $result = $this->invokeFraudApi($requestData);
            Log::write("BLACK-CHECK-RESULT:".json_encode($result), Log::INFO);
            if($result['final_score'] && $data['id']>0 ) {
                if($data['tongdun_final_score']<> $result['final_score']) {
                    D("Customer")->execute("UPDATE `customer` SET `tongdun_final_score`='".$result['final_score']."'  WHERE `id`='".$data['id']."'");
                }
            }
            if($result['application_id'] && $data['id']>0 ) {
                if($data['tongdun_application_id']<> $result['application_id']) {
                    D("Customer")->execute("UPDATE `customer` SET `tongdun_application_id`='".$result['application_id']."'  WHERE `id`='".$data['id']."'");
                }
            }
            if ($result["success"] && $result['final_decision'] != 'Reject')
            {
                return $data;
            }
            else {
                BusinessException::throwException(Constant::IN_BLACK_LIST);
            }
        }
        else {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }
    }


    /**
     * $params 请求参数
     * $timeout 超时时间
     * $connection_timeout 连接超时时间
     */
    function invokeFraudApi(array $params, $timeout = 10000, $connection_timeout = 10000)
    {
        $api_url = $this->apiUrl;
        $options = array(
            CURLOPT_POST => 1,            // 请求方式为POST
            CURLOPT_URL => $api_url,      // 请求URL
            CURLOPT_RETURNTRANSFER => 1,  // 获取请求结果
            // -----------请确保启用以下两行配置------------
            CURLOPT_SSL_VERIFYPEER => 1,  // 验证证书
            CURLOPT_SSL_VERIFYHOST => 2,  // 验证主机名
            // -----------否则会存在被窃听的风险------------
            CURLOPT_POSTFIELDS => http_build_query($params) // 注入接口参数
        );

        if (defined("CURLOPT_TIMEOUT_MS")) {
            $options[CURLOPT_NOSIGNAL] = 1;
            $options[CURLOPT_TIMEOUT_MS] = $timeout;
        } else {
            $options[CURLOPT_TIMEOUT] = ceil($timeout / 1000);
        }
        if (defined("CURLOPT_CONNECTTIMEOUT_MS")) {
            $options[CURLOPT_CONNECTTIMEOUT_MS] = $connection_timeout;
        } else {
            $options[CURLOPT_CONNECTTIMEOUT] = ceil($connection_timeout / 1000);
        }

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        if(!($response = curl_exec($ch))) {
            // 错误处理，按照同盾接口格式fake调用结果
            return array(
                "success" => "false",
                "reason_code" => "000:调用API时发生错误[".curl_error($ch)."]"
            );
        }
        curl_close($ch);
        return json_decode($response, true);
    }


} 